const { join, extname } = require('path')
const fs = require('fs')
const http = require('http')
const { createGzip } = require('zlib')
const url = require('url')
const mimes = require('./libs/mime')

// 网站根目录  url地址中的 / => www目录
const webRoot = join(__dirname, 'www')

// get数据获取
http.createServer((req, res) => {
  if (req.url != '/favicon.ico') {
    // query，就是浏览器访问的get参数集合
    let { pathname, query } = url.parse(req.url, true)
    pathname = pathname === '/' ? '/index.html' : pathname
    // 得到请求的对象服务器中真实的文件路径
    let filepath = join(webRoot, pathname)

    if (fs.existsSync(filepath)) {
      // 得到请求文件的扩展名
      const ext = extname(filepath).slice(1)
      // 得到扩展名
      const mime = mimes[ext]
      // 设置响应头
      res.setHeader('content-type', mime)
      // res.setHeader('Content-Encoding', 'gzip')
      let html;
      if ('html' === ext) {
        html = fs.readFileSync(filepath, 'utf-8');
        // html = html.replace('{{id}}', query.id)
        html = html.replace(/\{\{\s*(\w+)\s*\}\}/g, (preg,match) => {
          return query[match]
        })
      } else {
        html = fs.readFileSync(filepath)
      }
      res.end(html)
      // fs.createReadStream(filepath).pipe(createGzip()).pipe(res)
    } else {
      res.statusCode = 404
      res.end('not found')
    }


  }

}).listen(3000, '0.0.0.0')
